package com.opennews.openplatform.service;

import lombok.RequiredArgsConstructor;
import org.apache.seata.core.context.RootContext;
import org.apache.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class OrderService {
    private final ProductService productService;
    private final RestTemplate restTemplate;

    @GlobalTransactional
    public List<Map<String, Object>> queryList() {
        List<Map<String, Object>> orders = restTemplate.getForObject("lb://order-service/api/orders", List.class);

        List<String> productIds = orders.stream()
                .map(order -> (String) order.get("productId"))
                .collect(Collectors.toList());

        List<Map<String, Object>> products = productService.query(productIds);

        return orders.stream().map(order -> {
                    Map<String, Object> product = products.stream()
                            .filter(p -> p.get("id").equals(order.get("productId")))
                            .findFirst()
                            .orElse(null);

                    if (product != null) {
                        order.put("product", Map.of(
                                "id", product.get("id"),
                                "title", product.get("title")
                        ));
                    }

                    order.remove("productId");

                    return order;
                })
                .collect(Collectors.toList());
    }

    @GlobalTransactional
    public void placeOrder() {
        testTransaction();
        productService.testTransaction();
    }

    private void testTransaction() {
        restTemplate.postForObject("lb://order-service/api/orders", Map.of("id", "id-value"), Void.class);
    }
}
